package hello;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * @author Mark
 * @date 2020/5/25 17:52
 * @description 下载文件
 */
public class DownLoadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        /*
         * 1. 获取下载路径
         * 2. 下载名
         * 3. 浏览器支持下载
         * 4. 获取下载文件输入流
         * 5. 创建缓冲流
         * 6. 获取outputStream对象
         * 7. 将fileOutputStream写到缓冲流中
         * 8. 将outputStream输出到客户端
         * */

        String realPath = "D:\\git\\spring-study\\java-study-gitee\\Java-study\\simple\\target\\classes\\1.png";
        System.out.println("realPath = " + realPath);
        String fileName = realPath.substring(realPath.lastIndexOf("\\") + 1);
        resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        FileInputStream fileInputStream = new FileInputStream(realPath);
        int length;
        byte[] bytes = new byte[1024];
        ServletOutputStream outputStream = resp.getOutputStream();
        while ((length = fileInputStream.read()) > 0) {
            outputStream.write(bytes, 0, length);
        }
        outputStream.close();
        fileInputStream.close();
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}
